<?php

namespace app\admin\model;

use think\Model;

class CustomerModel extends BaseModel
{
    protected $name = 'customer';
    protected $json = ['address', 'connector', 'relationship'];
    protected $jsonAssoc = true;

    public static function getCustomerInfoByOpenid($openid, $platform)
    {
        return self::where('openid', $openid)->where('platform', $platform)->find();
    }

    public static function onBeforeInsert(Model $model)
    {
        $exists = self::whereOr([
            'label' => $model->label,
            'short_label' => $model->short_label,
        ])->find();
        if ($exists)
            api_return(500, '全称或简称重复');
    }

    public static function onBeforeUpdate(Model $model)
    {
        $where = [
            'label' => $model->label,
            'short_label' => $model->short_label,
        ];
        $exists = self::where(function ($query) use ($where) {
            $query->whereOr($where);
        })->where('id', '<>', $model->id)->find();
        if ($exists)
            api_return(500, '全称或简称重复');
    }

    /**
     * 设置用户余额
     * @param $customerId 用户id
     * @param $total_amount 金额，正负
     * @param $type 交易类型 1 回收收入； 2 红包收入； 3提现
     * @param $actionId 事件id
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function setBalance($customerId, $total_amount, $type, $actionId)
    {
        $customerInfo = CustomerModel::find($customerId);
        $p = [
            'customer_id' => $customerId,
            'old_balance' => $customerInfo->balance,
            'new_balance' => $customerInfo->balance + $total_amount,
            'type' => $type,
            'price' => $total_amount,
            'action_id' => $actionId
        ];
        if ($p['new_balance'] < 0) {
            api_return(500, '余额不足');
        }
        IncomeModel::editWithReturn($p);
        CustomerModel::where('id', '=', $customerId)->inc('balance', $total_amount)->update();
    }

    public function orderIn()
    {
        return $this->hasMany(OrderInModel::class);
    }
}
